package com.hxkcloud.patient.activitys;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.hxkcloud.patient.R;
import com.hxkcloud.patient.YjhApplication;
import com.hxkcloud.patient.adapter.DpatientEvalutionAdapter;
import com.hxkcloud.patient.beans.FileUploadBean;
import com.hxkcloud.patient.beans.PatientEvalutionBean;
import com.hxkcloud.patient.beans.PatientEvalutionWholeBean;
import com.hxkcloud.patient.config.UrlConfig;
import com.hxkcloud.patient.recorder.MediaManger;
import com.hxkcloud.patient.recorder.view.AudioRecorderButton;
import com.hxkcloud.patient.recorder.view.AudioRecorderLinearlayout;
import com.hxkcloud.patient.request.MessageCode;
import com.hxkcloud.patient.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.patient.utils.BrightnessUtils;
import com.hxkcloud.patient.utils.ImageVideoUtils;
import com.hxkcloud.patient.views.pulltorefreshlayout.PullToRefreshLayout;
import com.hxkcloud.patient.views.pulltorefreshlayout.PullableRecyclerView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by william_sun on 2016-10-11.
 * Description:医生端查看的患者康复评价
 */
public class DpatientEvalutionActivity extends BaseActivity implements View.OnClickListener, AudioRecorderLinearlayout.OnRecordingListener, PullToRefreshLayout.OnRefreshListener {

    //title
    private LinearLayout ll_title;
    private ImageView iv_back;
    private TextView tv_title;

    private EditText et_comment;
    private LinearLayout ll_voice;
    private TextView tv_voice;
    private ImageView iv_takevoice;
    private Button bt_submit;
    private PullToRefreshLayout refreshLayout;
    private PullableRecyclerView recyclerView;

    private String patientId;

    private PopupWindow popup_record;//录音popup
    private AudioRecorderButton bt_precord;
    private String voicePath;
    private String voiceLenght = "";
    private static final int DEL_VOICE = 11;

    private List<PatientEvalutionBean> evalutions;
    private int totalCount = 0;
    private int pageIndex = 1;
    private int pageSize = 15;

    private DpatientEvalutionAdapter adapter;

    private int voicePosition;
    private int delPosition;

    //两个按钮,delete
    private PopupWindow popup_easynotice;
    private TextView tv_easynotice_title;
    private TextView tv_easynotice_cancel;
    private TextView tv_easynotice_func;

    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {
            case MessageCode.NETWORKCODE_FILEUPLOAD_SUCCESS:
                List<FileUploadBean> paths = (List<FileUploadBean>) msg.obj;
                String path = paths.get(0).getFilePath();
                loading();
                String comment = et_comment.getText().toString().trim();
                YiJiaHuNetWorkUtils.addPatientEvalution(patientId, comment, path, voiceLenght, handler);
                break;
            case MessageCode.NETWORKCODE_FILEUPLOAD_FAILURE:
                if (msg.obj != null && !TextUtils.isEmpty((String) msg.obj)) {
                    toastMsg((String) msg.obj);
                    return;
                } else {
                    toastMsg(getResources().getString(R.string.fileuploadfail));
                }
                break;
            case MessageCode.NETWORKCODE_ADDPATIENTEVALUTION_SUCCESS:
                if (msg.obj != null && !TextUtils.isEmpty((String) msg.obj)) {
                    toastMsg((String) msg.obj);
                } else {
                    toastMsg(getResources().getString(R.string.datacommitsuccess));
                }
                //refresh list
                initData();
                et_comment.setText("");
                delSound();
                bt_submit.setBackgroundResource(R.drawable.bt_grey);
                break;
            case MessageCode.NETWORKCODE_ADDPATIENTEVALUTION_FAILURE:
                if (msg.obj != null && !TextUtils.isEmpty((String) msg.obj)) {
                    toastMsg((String) msg.obj);
                    return;
                } else {
                    toastMsg(getResources().getString(R.string.datacommitfail));
                }
                break;
            case MessageCode.NETWORKCODE_PATIENTEVALUTIONLIST_SUCCESS:
                PatientEvalutionWholeBean wholeBean = (PatientEvalutionWholeBean) msg.obj;
                if (wholeBean.getTotalcount() != null && !"null".equals(wholeBean.getTotalcount())) {
                    totalCount = Integer.valueOf(wholeBean.getTotalcount());
                }
                if (pageIndex == 1) {
                    evalutions.clear();
                    refreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                } else {
                    refreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                }
                evalutions.addAll(wholeBean.getList());
                adapter.setData(evalutions);
                break;
            case MessageCode.NETWORKCODE_PATIENTEVALUTIONLIST_FAILURE:
                if (msg.obj != null && !TextUtils.isEmpty((String) msg.obj)) {
                    toastMsg((String) msg.obj);
                    return;
                } else {
                    toastMsg(getResources().getString(R.string.datagetfail));
                }
                if (pageIndex == 1) {
                    refreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                } else {
                    refreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                }
                break;
            case MessageCode.NETWORKCODE_PATIENTEVALUTIONDELETE_SUCCESS:
                if (msg.obj != null && !TextUtils.isEmpty((String) msg.obj)) {
                    toastMsg((String) msg.obj);
                } else {
                    toastMsg(getResources().getString(R.string.datadeletesuccess));
                }
                //refresh list
                initData();
                break;
            case MessageCode.NETWORKCODE_PATIENTEVALUTIONDELETE_FAILURE:
                if (msg.obj != null && !TextUtils.isEmpty((String) msg.obj)) {
                    toastMsg((String) msg.obj);
                    return;
                } else {
                    toastMsg(getResources().getString(R.string.datadeletefail));
                }
                break;
            case MessageCode.NETWORKCODE_DOWNLOADVOICE_SUCCESS:
//                File file = (File) msg.obj;
                if (!MediaManger.isPlaying()) {
                    evalutions.get(voicePosition).setIsVoicePlaying(true);
                    adapter.notifyItemChanged(voicePosition);
//                    adapter.setData(datas);
                    MediaManger.playSound(ImageVideoUtils.getDataCacheDir(mContext) + "/voice.amr", new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            evalutions.get(voicePosition).setIsVoicePlaying(false);
//                            adapter.setData(datas);
                            adapter.notifyItemChanged(voicePosition);
                        }
                    });
                }
                break;
            case MessageCode.NETWORKCODE_DOWNLOADVOICE_FAILURE:
                toastMsg(getResources().getString(R.string.voicedownloadfail));
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dpatientevalution);

        patientId = getIntent().getStringExtra("patientid");

        initView();
        initPopup();
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    @Override
    protected void initView() {
        ll_title = (LinearLayout) findViewById(R.id.ll_title);
        iv_back = (ImageView) findViewById(R.id.iv_title_back);
        tv_title = (TextView) findViewById(R.id.tv_title_title);

        setTitlePadding(ll_title);
        iv_back.setVisibility(View.VISIBLE);
        tv_title.setText(getResources().getText(R.string.evalution));
        iv_back.setOnClickListener(this);

        et_comment = (EditText) findViewById(R.id.et_dpatienteva_comment);
        ll_voice = (LinearLayout) findViewById(R.id.ll_dpatienteva_voice);
        tv_voice = (TextView) findViewById(R.id.tv_dpatienteva_voice);
        iv_takevoice = (ImageView) findViewById(R.id.iv_dpatienteva_takevoice);
        bt_submit = (Button) findViewById(R.id.bt_dpatienteva_submit);
        refreshLayout = (PullToRefreshLayout) findViewById(R.id.refreshlayout_dpatientevalution);
        recyclerView = (PullableRecyclerView) findViewById(R.id.recyclerview_dpatientevalution);

        ll_voice.setOnClickListener(this);
        iv_takevoice.setOnClickListener(this);
        bt_submit.setOnClickListener(this);

        et_comment.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s.toString())) {
                    bt_submit.setBackgroundResource(R.drawable.bt_red);
                } else {
                    if (!TextUtils.isEmpty(voicePath)) {
                        bt_submit.setBackgroundResource(R.drawable.bt_red);
                    } else {
                        bt_submit.setBackgroundResource(R.drawable.bt_grey);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        LinearLayoutManager mLayoutManager = new LinearLayoutManager(mContext);
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(mLayoutManager);
        refreshLayout.setOnRefreshListener(this);

        evalutions = new ArrayList<>();
        adapter = new DpatientEvalutionAdapter(mContext, evalutions, new DpatientEvalutionAdapter.evalutionListener() {
            @Override
            public void onDelete(int position) {
                delPosition = position;
                popup_easynotice.showAtLocation(ll_title, Gravity.CENTER, 0, 0);
                BrightnessUtils.lightOff(DpatientEvalutionActivity.this);
            }

            @Override
            public void onVoice(int position) {
                if (!MediaManger.isPlaying()) {
                    String url = evalutions.get(position).getVoiceUrl();
                    if (!TextUtils.isEmpty(url)) {
                        YiJiaHuNetWorkUtils.downloadFile(UrlConfig.image_host + url.replace(".amr.mp3", ".amr"), mContext, handler);
                        voicePosition = position;
                    } else {
                        toastMsg(R.string.downloadurl_wrong);
                    }
                }
            }
        });
        recyclerView.setAdapter(adapter);
    }

    private void initPopup() {
        popup_record = new PopupWindow(this);
        View viewRecord = LayoutInflater.from(mContext).inflate(R.layout.popup_record, null);
        popup_record.setContentView(viewRecord);
        popup_record.setWidth(screenWidth);
        popup_record.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popup_record.setFocusable(true);
        popup_record.setTouchable(true);
        popup_record.setOutsideTouchable(true);
        popup_record.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popup_record.setAnimationStyle(R.style.popupwindow_anim_default);

        bt_precord = (AudioRecorderButton) viewRecord.findViewById(R.id.bt_record_sound);
        bt_precord.setOnRecordingListener(this);
        popup_record.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                BrightnessUtils.lightOn(DpatientEvalutionActivity.this);
            }
        });

        //easynotice
        popup_easynotice = new PopupWindow(this);
        View viewNotice = LayoutInflater.from(this).inflate(R.layout.popup_easynotice, null);
        popup_easynotice.setContentView(viewNotice);

        popup_easynotice.setWidth((int) (screenWidth * 0.7));
        popup_easynotice.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popup_easynotice.setFocusable(true);
        popup_easynotice.setTouchable(true);
        popup_easynotice.setOutsideTouchable(true);
        popup_easynotice.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popup_easynotice.setAnimationStyle(R.style.popupwindow_anim_alpha);

        tv_easynotice_title = (TextView) viewNotice.findViewById(R.id.tv_easynotice_title);
        tv_easynotice_cancel = (TextView) viewNotice.findViewById(R.id.tv_easynotice_cancel);
        tv_easynotice_func = (TextView) viewNotice.findViewById(R.id.tv_easynotice_func);

        tv_easynotice_title.setText(R.string.deltherecord);
        tv_easynotice_cancel.setText(R.string.cancel);
        tv_easynotice_func.setText(R.string.sure);

        tv_easynotice_cancel.setOnClickListener(this);
        tv_easynotice_func.setOnClickListener(this);

        popup_easynotice.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                BrightnessUtils.lightOn(DpatientEvalutionActivity.this);
            }
        });
    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void initData() {
        loading();
        pageIndex = 1;
        YiJiaHuNetWorkUtils.patientEvalutionList(patientId, pageIndex, pageSize, handler);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_back:
                finish();
                break;
            case R.id.ll_dpatienteva_voice:
                if (!TextUtils.isEmpty(voicePath)) {
                    Intent iRecorder = new Intent(mContext, RecorderActivity.class);
                    iRecorder.putExtra("path", voicePath);
                    startActivityForResult(iRecorder, DEL_VOICE);
                }
                break;
            case R.id.iv_dpatienteva_takevoice:
                closeInputMethodManager();
                popup_record.showAtLocation(ll_title, Gravity.BOTTOM, 0, 0);
                BrightnessUtils.lightOff(DpatientEvalutionActivity.this);
                break;
            case R.id.bt_dpatienteva_submit:
                String comment = et_comment.getText().toString().trim();
                if (TextUtils.isEmpty(comment) && TextUtils.isEmpty(voicePath)) {
//                    toastMsg(R.string.pleaseinputcommentvoice);
                    return;
                }
                loading();
                if (!TextUtils.isEmpty(voicePath)) {
                    List<File> voices = new ArrayList<>();
                    voices.add(new File(voicePath));
                    YiJiaHuNetWorkUtils.FileUpload(voices, YjhApplication.file_media, handler);
                } else {
                    YiJiaHuNetWorkUtils.addPatientEvalution(patientId, comment, "", voiceLenght, handler);
                }
                break;
            case R.id.tv_easynotice_cancel:
                popup_easynotice.dismiss();
                break;
            case R.id.tv_easynotice_func:
                popup_easynotice.dismiss();
                loading();
                YiJiaHuNetWorkUtils.patientEvalutionDelete(evalutions.get(delPosition).getEvaluationId(), handler);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == DEL_VOICE) {
                delSound();

                if (!TextUtils.isEmpty(et_comment.getText().toString())) {
                    bt_submit.setBackgroundResource(R.drawable.bt_red);
                } else {
                    bt_submit.setBackgroundResource(R.drawable.bt_grey);
                }
            }
        }
    }

    public void delSound() {
        if (!TextUtils.isEmpty(voicePath)) {
            deleteAudio();
            ll_voice.setVisibility(View.INVISIBLE);
            iv_takevoice.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        deleteAudio();
    }

    public void deleteAudio() {
//        if (!TextUtils.isEmpty(bt_psound.getmAudioManager().getCurrentFilePath())) {
//            MediaManger.release();
//            File file = new File(bt_psound.getmAudioManager().getCurrentFilePath());
//            if (file.exists())
//                file.delete();
//            bt_psound.getmAudioManager().setCurrentFilePath("");
//            voicePath = "";
//        }
        if (!TextUtils.isEmpty(voicePath)) {
            MediaManger.release();
            File file = new File(voicePath);
            if (file.exists())
                file.delete();
            bt_precord.getmAudioManager().setCurrentFilePath("");
            voicePath = "";
        }
    }


    @Override
    public void onFinish(float seconds, String filePath) {
        ll_voice.setVisibility(View.VISIBLE);
        iv_takevoice.setVisibility(View.INVISIBLE);
        voiceLenght = Math.round(seconds) + "";
        tv_voice.setText("\"" + Math.round(seconds));
        voicePath = filePath;
        popup_record.dismiss();

        bt_submit.setBackgroundResource(R.drawable.bt_red);
    }

    @Override
    public void stateNormal() {

    }

    @Override
    public void stateRecording() {

    }

    @Override
    public void stateWantToCancel() {

    }

    @Override
    public void click(String filePath) {

    }

    @Override
    public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
        loading();
        pageIndex = 1;
        YiJiaHuNetWorkUtils.patientEvalutionList(patientId, pageIndex, pageSize, handler);
    }

    @Override
    public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
        if (evalutions.size() >= totalCount) {
            toastMsg(R.string.nomore);
            refreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
        } else {
            loading();
            pageIndex++;
            YiJiaHuNetWorkUtils.patientEvalutionList(patientId, pageIndex, pageSize, handler);
        }
    }
}
